All files / src/app/api/admin/orders/[orderId] route.ts

96.35% Statements 185/192
66.66% Branches 18/27
100% Functions 2/2
96.35% Lines 185/192

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 1931x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x     4x 4x 4x 4x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x     8x 8x 8x 8x 1x 1x 7x 7x 7x 7x 8x 2x 2x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 4x 4x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 8x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 8x 8x 8x 8x 8x 8x 1x 1x 1x  
export const dynamic = "force-dynamic";
 
import { NextRequest, NextResponse } from 'next/server';
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";
import { prisma } from "@/lib/prisma";
import { emitOrderUpdate } from "@/lib/socket/emitters";
import { emailService } from "@/lib/email/emailService";
import { logger } from "@/lib/logging";
import { z } from "zod";
import { Order } from "@prisma/client";
 
// Validation schema for PATCH request
const updateOrderStatusSchema = z.object({
  status: z.enum(["PROCESSING", "SHIPPED", "DELIVERED", "CANCELLED"] as const, {
    message: "Invalid status" }),
  // Optional shipping info for SHIPPED status
  trackingNumber: z.string().optional(),
  carrier: z.string().optional(),
  estimatedDelivery: z.string().optional() });
 
// Type for order with includes
type OrderWithDetails = Order & {
  user: { id: number; name: string | null; email: string };
  items: Array<{
    id: number;
    quantity: number;
    price: number;
    product: {
      id: number;
      title: string;
      price: number;
      images: Array<{ url: string }>;
    };
  }>;
};
 
/**
 * GET /api/admin/orders/[orderId]
 * Get order details
 */
async function handleGet(
  _request: NextRequest,
  context: RouteContext | undefined
): Promise<NextResponse<ApiSuccessResponse<OrderWithDetails> | ApiErrorResponse>> {
  if (!context?.params) {
    throw ApiError.invalidId("order");
  }
  const resolvedParams = await context.params;
  const orderId = parseInt(resolvedParams.orderId);
 
  if (isNaN(orderId)) {
    throw ApiError.badRequest("Invalid order ID");
  }
 
  const order = await prisma.order.findUnique({
    where: { id: orderId },
    include: {
      user: true,
      items: {
        include: {
          product: {
            select: {
              id: true,
              title: true,
              price: true,
              images: { select: { url: true }, take: 1 } } } } } } });
 
  if (!order) {
    throw ApiError.notFound("Order not found");
  }
 
  return successResponse(order);
}
 
/**
 * PATCH /api/admin/orders/[orderId]
 * Update order status
 */
async function handlePatch(
  request: NextRequest,
  context: RouteContext | undefined
): Promise<NextResponse<ApiSuccessResponse<Order> | ApiErrorResponse>> {
  if (!context?.params) {
    throw ApiError.invalidId("order");
  }
  const resolvedParams = await context.params;
  const orderId = parseInt(resolvedParams.orderId);
 
  if (isNaN(orderId)) {
    throw ApiError.badRequest("Invalid order ID");
  }
 
  const body = await request.json();
  const validation = updateOrderStatusSchema.safeParse(body);
 
  if (!validation.success) {
    throw ApiError.validation("Validation failed", validation.error.flatten().fieldErrors);
  }
 
  const { status, trackingNumber, carrier, estimatedDelivery } = validation.data;
 
  const order = await prisma.order.update({
    where: { id: orderId },
    data: { status },
    include: {
      user: { select: { id: true, name: true, email: true } },
      items: {
        include: {
          product: { select: { title: true } }
        }
      }
    }
  });
 
  // Send email notifications based on status change
  const orderNumber = `ORD-${orderId.toString().padStart(6, '0')}`;
 
  if (status === 'SHIPPED' && order.user.email) {
    // Send shipping notification
    emailService.sendShippingNotification({
      id: orderId,
      orderNumber,
      userId: order.userId,
      customerEmail: order.user.email,
      customerName: order.user.name || 'Valued Customer',
      trackingNumber: trackingNumber || 'N/A',
      carrier: carrier || 'Standard Shipping',
      estimatedDelivery: estimatedDelivery
        ? new Date(estimatedDelivery)
        : new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) // Default: 7 days
    }).catch((err) => {
      logger.error("Failed to queue shipping notification email", err instanceof Error ? err : new Error(String(err)), { category: 'API', orderId });
    });
  } else if (status === 'DELIVERED' && order.user.email) {
    // Send delivered notification
    emailService.sendOrderDelivered({
      id: orderId,
      orderNumber,
      userId: order.userId,
      customerEmail: order.user.email,
      customerName: order.user.name || 'Valued Customer'
    }).catch((err) => {
      logger.error("Failed to queue delivery notification email", err instanceof Error ? err : new Error(String(err)), { category: 'API', orderId });
    });
 
    // Also queue a review request (with delay)
    emailService.sendReviewRequest({
      id: orderId,
      orderNumber,
      userId: order.userId,
      customerEmail: order.user.email,
      customerName: order.user.name || 'Valued Customer',
      items: order.items.map(item => ({
        name: item.product.title,
        productId: item.productId
      }))
    }).catch((err) => {
      logger.error("Failed to queue review request email", err instanceof Error ? err : new Error(String(err)), { category: 'API', orderId });
    });
  }
 
  // Emit real-time order status update to customer and admins
  const statusMessages: Record<string, string> = {
    PROCESSING: "Your order is being processed",
    SHIPPED: "Your order has been shipped",
    DELIVERED: "Your order has been delivered",
    CANCELLED: "Your order has been cancelled"
  };
 
  emitOrderUpdate(
    order.userId.toString(),
    orderId.toString(),
    {
      orderId: orderId.toString(),
      status: order.status,
      timestamp: new Date().toISOString(),
      message: statusMessages[order.status] || `Order status updated to ${order.status}`
    }
  );
 
  return successResponse(order);
}
 
export const GET = withErrorHandling(withAdmin(handleGet));
export const PATCH = withErrorHandling(withAdmin(handlePatch));